import { editProfileAction } from '@/store/actions/profile'
import { RootState } from '@/types/store'
import { NavBar, Popup, Input, TextArea, Toast } from 'antd-mobile'
import { useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import style from './index.module.scss'

export type InputPopType = {
  visible: boolean
  close: () => void
  type: 'name' | 'intro'
}

function InputPop({ visible, close, type }: InputPopType) {
  // 仓库的数据
  const { profile } = useSelector((state: RootState) => state.profile)
  const [input, setInput] = useState('')
  const dispatch = useDispatch()

  // 弹框显示时才真正填充数据
  useEffect(() => {
    if (visible === true) {
      // 显示
      setInput(type === 'name' ? profile.name : profile.intro || '')
    }
  }, [visible])

  // 提交数据更改
  const submit = async () => {
    await dispatch(editProfileAction(type, input))
    // 能到这里 说明更新成功
    Toast.show({
      icon: 'success',
      content: '数据修改完毕!',
    })
    close()
  }

  return (
    // position 位置
    // bodyStyle 设置的样式
    // destroyOnClose 设置关闭时清空数据
    <Popup destroyOnClose visible={visible} position='right' bodyStyle={{ width: '100vw' }}>
      {/* 顶部导航
        style 自定义了底部的边框
      */}
      <NavBar
        onBack={close}
        style={{
          '--border-bottom': '1px #eee solid',
        }}
        right={
          <span onClick={submit} className={style.submit}>
            提交
          </span>
        }
      >
        编辑{type === 'name' ? '昵称' : '介绍'}
      </NavBar>
      {/* 输入框 */}
      {type === 'name' && (
        <div className={style.nameWrapper}>
          <Input
            value={input}
            onChange={(val) => {
              setInput(val)
            }}
            placeholder='请输入内容'
          />
        </div>
      )}

      {/* 文本域 */}
      {type === 'intro' && (
        <div className={style.infoWrapper}>
          <TextArea
            value={input}
            onChange={(val) => {
              setInput(val)
            }}
            defaultValue={'北极星垂地，\n东山月满川。'}
            showCount
          />
        </div>
      )}
    </Popup>
  )
}

export default InputPop
